#coding:utf-8
import socket
import threading
from multiprocessing import Process, Queue
#import dataParse
import struct
import pymysql
import datetime
import select
import os 
import json
import traceback
import sys
import time
import http.client
from urllib.request import urlopen

sys.getdefaultencoding()
OBJ_HOST = "139.224.35.125"
OBJ_URL = "/aijukex/op/op_powerSupplyTest"
PORT = 80
host1 = "139.224.35.125"
url1 = "http://www.live-ctrl.com/aijukex/op/op_queryPowerWarn"
url2 = "http://www.live-ctrl.com/aijukex/op/op_powerWarnDatas"
port1 = 80
def list_to_json(listData):
	list_json = []
	#for elem in listData:
	list_json.append((listData))
	dataJson = json.dumps(list_json,ensure_ascii=False)
	return dataJson

def httpSend(host, url, port, data_str):
	conn = http.client.HTTPConnection(host, port, timeout = 5)
	data = {'data':data_str}
	headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "*/*"}
	params = urllib.parse.urlencode(data)
	conn.request("POST", url, params, headers)

	response = conn.getresponse()
	data = response.read()
	conn.close()
	return data

def read(chmer):
    conn = pymysql.connect("localhost", "root", "1234","moyan",charset="utf8")
    print("查询数据库》》》连接成功")
    cursor = conn.cursor()
    #sql = """SELECT * FROM historydata WHERE name='电视' ORDER BY id DESC LIMIT 1"""
    cursor.execute("SELECT * FROM historydata  WHERE name='空调' and id_id = %d ORDER BY id DESC LIMIT 1 " % chmer)
    data = cursor.fetchall()
    dic = {}
    for elem in data:
        #print(elem)
        dic['id'] = elem[1]
        dic['name'] = elem[2]
        dic['power'] = elem[3]
        dic['state'] = elem[4]
    dataJson = list_to_json(dic)
    if dic:
	    try:
	    	print("正在发送查询数据到爱居客")
	    	httpSend(OBJ_HOST, OBJ_URL, PORT, dataJson)
	    	print("爱居客查询数据发送成功",dataJson)
	    except :
	    	print("数据查询失败")

    #sql = """SELECT * FROM historydata WHERE name='空调' ORDER BY id DESC LIMIT 1"""
    cursor.execute("SELECT * FROM historydata  WHERE name='电视' and id_id = %d ORDER BY id DESC LIMIT 1 " % chmer)
    data = cursor.fetchall()
    dic1 = {}
    for elem in data:
        #print(elem)
        dic1['id'] = elem[1]
        dic1['name'] = elem[2]
        dic1['power'] = elem[3]
        dic1['state'] = elem[4]
    dataJson = list_to_json(dic1)
    if dic1:
	    try:
	    	print("正在发送查询数据到爱居客")
	    	httpSend(OBJ_HOST, OBJ_URL, PORT, dataJson)
	    	print("爱居客查询数据发送成功",dataJson)
	    except :
	    	print("数据查询失败")


    #sql = """SELECT * FROM historydata WHERE name='浴霸' ORDER BY id DESC LIMIT 1"""
    cursor.execute("SELECT * FROM historydata  WHERE name='浴霸' and id_id = %d ORDER BY id DESC LIMIT 1 " % chmer)
    data = cursor.fetchall()
    dic2 = {}
    for elem in data:
        #print(elem)
        dic2['id'] = elem[1]
        dic2['name'] = elem[2]
        dic2['power'] = elem[3]
        dic2['state'] = elem[4]
    dataJson = list_to_json(dic2)
    if dic2:
	    try:
	    	print("正在发送查询数据到爱居客")
	    	httpSend(OBJ_HOST, OBJ_URL, PORT, dataJson)
	    	print("爱居客查询数据发送成功",dataJson)
	    except :
	    	print("数据查询失败")


    #sql = """SELECT * FROM historydata WHERE name='灯' ORDER BY id DESC LIMIT 1"""
    cursor.execute("SELECT * FROM historydata  WHERE name='灯' and id_id = %d ORDER BY id DESC LIMIT 1 " % chmer)
    data = cursor.fetchall()
    dic3 = {}
    for elem in data:
        #print(elem)
        dic3['id'] = elem[1]
        dic3['name'] = elem[2]
        dic3['power'] = elem[3]
        dic3['state'] = elem[4]
    dataJson = list_to_json(dic3)
    if dic3:
	    try:
	    	print("正在发送查询数据到爱居客")
	    	httpSend(OBJ_HOST, OBJ_URL, PORT, dataJson)
	    	print("爱居客查询数据发送成功",dataJson)
	    except :
	    	print("数据查询失败")

    conn.close()


def server(q):
	global address,port,sock 
	address = "0.0.0.0"
	port = 8800
	sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	epoll = select.epoll()  
	#获取创建好的sock的文件描述符  
	fd = sock.fileno()  
	sock.bind((address,port))  
	sock_dict = {}  
	sock_dict[fd] = sock
	shumeipai ={}  
	#对该sock进行注册  
	epoll.register(fd,select.EPOLLIN)  
	sock.listen(5)  
	while True:
		events = epoll.poll(1)
		for fileno,event in events:#获取到的文件描述符和sock的相同就说明是一个新的连接
			if fileno == fd:
				(client,address) = sock.accept()

				#print ("来者地址",address)
				client.setblocking(0)#将新的连接进行注册，用来接收消息
				epoll.register(client.fileno(),select.EPOLLIN)
				sock_dict[client.fileno()] = client
			elif event & select.EPOLLIN:   #有可读事件激活
				#print ("fileno:",fileno)#返回套接字的文件描述符
				data = sock_dict[fileno].recv(128)
				if len(data) == 0:
					print ("client %d is not connected"%fileno )
					epoll.unregister(fileno)
				else:
					try:
						if 'name' in data.decode():
								print ("收到树莓派来信",data.decode())
								datas =  data.decode()
								q.put(datas)
								#print("来者地址",sock_dict[fileno])
								datas=json.loads(datas)
								i=(datas[0]['id'])
								#print(i,type(i))
								shumeipai[i]=fileno
								print(shumeipai[i])

						if 'action' in data.decode() and 'search' not in data.decode():
								print("收到爱菊客来信，正在发送到树莓派",data)
								zhiling = data.decode()
								j = int((zhiling.split(';')[0]).split('=')[-1])
								print(j,type(j))
								try:
										sock_dict[shumeipai[int(j)]].send(data)
										print("aijuke",fileno)
								except:
										print("没有这个树莓派")

						if 'search' in data.decode():
								print("收到查询消息",data)
								message = data.decode()
								k = int((message.split(';')[0]).split('=')[-1])
								#print(k,type(k))
								read(k)
					except:
							print("不明请求",data)
                                                                        

					
def wirteDB(data):
	#写入数据库
	# tmp=[]
	# dat = (data[0], data[1],data[2],datetime.datetime.now())
	# tmp.append(dat)
	conn = pymysql.connect("localhost", "root", "1234","moyan",charset="utf8")
	print("连接成功")
	# 使用cursor()方法获取操作游标
	cursor = conn.cursor()
	#2. SQL 插入语句
	sql = """INSERT INTO historydata(id_id, name, power, state, ntime) VALUES ( '%d', '%s', '%s', '%s', '%s')"""
	   # 执行sql语句
	cursor.execute((sql %(data[0], data[1], data[2], data[3], datetime.datetime.now())).encode('utf-8'))
	#cursor.executemany(sql ,tmp)
	conn.commit()
	print("数据写入数据库成功",datetime.datetime.now())
	# 提交到数据库执行
	# 关闭数据库连接
	conn.close()

def WriteDBProcess(q):
	while True:
		try:
			data = q.get()
			data=json.loads(data)
			#data = data.encode('utf-8')
			#data=[{"name": "电水壶", "id": 1234, "power": "15", "state": "0"}]
			for elem in data:
				#print(elem['name'].encode('utf-8'))
				datas =[]
				datas.append(elem['id'])
				datas.append(elem['name'])
				datas.append(elem['power'])
				datas.append(elem['state'])
				#print(elem['id'],elem['name'],elem['state'],elem['power'])
			wirteDB(datas)

			#print(data,type(data))
		except:
			print("mysql未能取到数据")

			


def httpGet(q):
	while True:
		conn = http.client.HTTPConnection("139.224.35.125",80,timeout = 1)
		conn.request(method="GET", url="http://www.live-ctrl.com/aijukex/op/op_queryPowerWarn")
		response = conn.getresponse()
		response = urlopen("http://www.live-ctrl.com/aijukex/op/op_queryPowerWarn").read().decode('utf8')
		obj = json.loads(response)
		#print(obj,type(obj))
		for elem in obj:
			#print(elem)
			elem['id']=str(elem['id'])
			#nnn = obj[0]['name']
			www = '1234'
			conn = pymysql.connect("localhost", "root", "1234", "moyan", charset="utf8")
			#print("查询数据库》》》连接成功")
			cursor = conn.cursor()
			cursor.execute("SELECT * FROM historydata  WHERE name LIKE %s and id_id = %s ORDER BY id DESC LIMIT 1 " , (elem['name'] , elem['id']) )
			data = cursor.fetchall()
			if data:
				print("查询到%s数据"%elem['name'])
				if int(data[0][3]) > int(elem['warnPower']):
					dic = {}
					for elem in data:
						# print(elem)
						dic['id'] = elem[1]
						dic['name'] = elem[2]
						dic['power'] = elem[3]
						dic['state'] = elem[4]
					dataJson = list_to_json(dic)
					try:
						htttpSend("139.224.35.125", "http://www.live-ctrl.com/aijukex/op/op_powerWarnDatas", 80, dataJson)
						print("报警数据上报成功")
					except:
						print("报警数据上报失败")
				else:
					print("目前没有%s报警数据"%(elem['name']))
		conn.close()
		time.sleep(60)
def main():
	while True:
		try:
			q = Queue()
			#启动进程server
			prev=Process(target=server, args=(q,))
			prevget = Process(target=httpGet, args=(q,))
			#启动京城WriteDB
			ploc=Process(target=WriteDBProcess,args=(q,))
			prev.start()
			prevget.start()
			ploc.start()
			break
		except:
			print("服务器正在重新启动")
			time.sleep(3)
			continue

if __name__ == '__main__':
	main()
